package whisper.api.gateway.frame.auth.repository;

import org.apache.commons.lang.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
import whisper.api.gateway.frame.Constant;
import whisper.api.gateway.frame.auth.config.DbConfig;
import whisper.api.gateway.frame.auth.domain.Role;

import java.util.List;


/**
 * Created by JT on 2017/9/22.
 */
@Repository
public class RoleRepositoryImpl implements RoleRepository {



    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Override
    public void insertRole(Role role) {
        String[] roleTableColumns = (String[]) ArrayUtils.remove(DbConfig.TABLE_COLUMNS_ROLE, 0);
        String columns = String.join(",", roleTableColumns);
        String sql = String.format("INSERT INTO %s(%s) VALUES(?, ?)", DbConfig.TABLE_NAME_ROLE, columns);
        Object[] params = new Object[]{Constant.ROLE_PREFIX + role.getCode(), role.getName()};
        jdbcTemplate.update(sql, params);
    }


    /**
     * 查询用户所有角色
     *
     * @param uid ： 用户ID
     * @return
     */
    @Override
    public List<Role> findRolesByUid(Integer uid) {
        String sql = String.format("SELECT R.ID AS ID, R.CODE AS CODE, R.NAME AS NAME FROM %s AS UR,%s AS R WHERE UR.RID = R.ID AND UR.UID=?",
                DbConfig.TABLE_NAME_USER_ROLE, DbConfig.TABLE_NAME_ROLE);
        Object[] params = new Object[]{uid};
        return  jdbcTemplate.query(sql, params, new BeanPropertyRowMapper<>(Role.class));
    }
}
